package com.liuxiaoyu.toptalks.controller;

import com.alibaba.fastjson.JSONObject;
import com.liuxiaoyu.toptalks.common.R;
import com.liuxiaoyu.toptalks.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
@RequestMapping("/user")
public class UserController {
    @Value("${wx.app_id}")
    private String appid;
    @Value("${wx.app_secret}")
    private String appsecret;
    @GetMapping("/login/{code}")
    public R<String> WeixinApiLogin(@PathVariable String code){
        //得到微信返回code临时票据
        //拿着code + 小程序id + 小程序密钥 请求微信接口服务
        //请求微信接口服务，返回两个值session_key和openId
        StringBuffer url = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/jscode2session")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&js_code=%s")
                .append("&grant_type=authorization_code");
        String tokenUrl = String.format(url.toString(), appid, appsecret, code);
        String result;
        try {
            result = HttpClientUtils.get(tokenUrl);
        }catch (Exception e){
            throw new RuntimeException();
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        String sessionKey = jsonObject.getString("session_key");
        String openid = jsonObject.getString("openid");
        return null;
    }
    @GetMapping
    public String hello(){
        return "hello";
    }
}
